package com.zhanglijie.theory.readwrite;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import co.paralleluniverse.strands.dataflow.Var;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/14 0014 15:44
 */
public class TextData {
    private final char[] buffer;
    private final MyReadWriteLock lock = new MyReadWriteLock();
    public TextData(int size){
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            this.buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        lock.readLock();
        try {
            return doRead();
        }finally {
            lock.readUnLock();
        }
    }

    private char[] doRead()  {
        char[] chars = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            chars[i] = buffer[i];
        }
        try {
            Thread.sleep(1000);
        }catch (Exception e){}
        return chars;
    }

    public void write(char newChar) throws InterruptedException {
        lock.writeLock();
        try {
            doWrite(newChar);
        }finally {
            lock.writeUnLock();
        }
    }
    private void doWrite(char newChar){
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = newChar;
        }
        try {
            Thread.sleep(50);
        }catch (Exception e){}
    }
}
